<?php
class itemsController extends Controller {

    var $pagelock = false;

    function __construct() {
        parent::__construct();

        $this->pagesize = 25;

        //推荐人
        if ($this->get['camefrom']) {
            $user =& getController('users');
            if ($tmp = $user->byName($this->get['camefrom'])) {
                if ($tmp['id'] && ($tmp['id'] != $this->session['id']) ) setcookie('camefrom', $tmp['id'], time()+3600*24*365*10, '/');
            }
        }
    }

    function whatNew($pagesize=15) {
        //优先显示补货
        $this->request['sort']      = ' IF(stocked,stocked,created) ';
        $this->request['sortorder'] = 'desc';
        $this->pagesize = $pagesize;
        $this->pagelock = true;

        if ($this->request['xml']=='xml') $this->pagesize = 20;

        $this->_var['where'] = 'stocknum > 0 ';

        return $this->itemsList();
    }

    function whatHot() {
        $this->request['sort']      = 'click';
        $this->request['sortorder'] = 'desc';
        $this->pagesize = 15;
        $this->pagelock = true;

        if ($this->request['xml']=='xml') $this->pagesize = 20;

        $this->_var['where'] = 'stocknum > 0 ';

        //按时间统计热门物品
        if ((int)$this->request['timelimit']) {
            $timelimit = time() - $this->request['timelimit']*3600*24;
            $this->_var['where'] .= ' AND updated>' .$timelimit;
        }

        return $this->itemsList();
    }

    function whatMiss() {
        $this->request['sort']      = 'click';
        $this->request['sortorder'] = 'desc';
        $this->pagesize = 12;
        $this->pagelock = true;

        $this->_var['where'] = 'stocknum <=0 ';

        return $this->itemsList();
    }

    function whatOffer() {
        $this->request['sort']      = 'updated';
        $this->request['sortorder'] = 'desc';
        $this->pagesize = 15;
        $this->pagelock = true;

        $this->_var['where'] = 'price2 > price1 AND stocknum > 0';

        return $this->itemsList();
    }

    function frontItemShow() {
        $this->request['id'] = $this->request['id'] ? $this->request['id'] : 0;

        $result = $this->itemsList();

        //没有指定 pid 时
        if ($result['pid']==0) {
            $tmp = $this->model->getItemsClass($this->request['id']);
            $result['pid'] = $this->request['pid'] = $tmp[0];
        }

        $tmp = $this->catsList();
        $result['cats'] = $tmp['list'];

        if ($result['tags']) {
            //根据 tagid 取得相关物品
            unset($tmp);
            foreach ($result['tags'] as $tag_v) $tmp['ids'][] = $tag_v['id'];
            $tmp['limit']   = 10;
            $tmp['deid']    = $this->request['id'];
            $tmp = $this->model->getItemsByTagId($tmp);
            $result['related']  = $tmp['list'];
        }

        //测试是否在用户的wishlist中
        if (count($result['list']['list']) && $this->session['login'] && $this->session['id']) {
            $wishlist =& getController('wishlist');
            $result['iswishlist'] = $wishlist->isUserWish($this->request['id'], $this->session['id']);
        }

        //测试是否来自wishlist点击 items.php/100?wish=1ff1de774005f8da13f42943881c655f
        if ($this->request['wish']) {
            $wishlist =& getController('wishlist');
            $result['wish'] = $wishlist->wishRequest();
            if ($result['wish']['uid'])
                $this->session['wish'] = $result['wish'];
            else
                unset($this->session['wish']);
        }

        return $result;
    }

    //按分类ID查看 $_GET['pid']
    function frontItemsList() {
        //用户自定义排序
        switch($this->request['o']) {
            case '1':           $sort = 'name'; $sortorder = 'asc'; break;
            case '2':           $sort = 'price1'; $sortorder = 'asc'; break;
            default: case '3':  $sort = 'updated'; $sortorder = 'desc'; break;
            case '4':           $sort = 'click'; $sortorder = 'desc'; break;
        }

        //$this->_var['where'] = 'stocknum > 0 ';

        //Ajax Search
        if ($this->request['ajaxfilter'])   {
            //$this->request['s'] = $this->request['ajaxfilter'];
            $this->_var['where'] = "name like '". addslashes($this->request['ajaxfilter']) ."%'";
            $sort = 'click';
            $this->request['pagesize'] = 10;
        }
        if ($this->get['filter']) $this->request['s'] = $this->get['filter'];

        $this->request['sort']      = 'stocknum&&1 DESC,'.$sort;
        $this->request['sortorder'] = $sortorder;

        $result = $this->itemsList();

        //TODO Move To Plugins
        //For OpenSearch
        if ($this->request['ajaxfilter'] && $this->request['output'] == 'fxjson') {
            $fxjson[0] = $this->request['ajaxfilter'];
            foreach ($result['list']['list'] as $v) {
                $fxjson[1][] = $v['name'];
            }
            echo json_encode($fxjson);
            die;
        }

        $this->request['sortorder'] = 'asc';
        $tmp = $this->catsList();
        $result['cats'] = $tmp['list'];

        return $result;
    }

    function itemsList($v="") {

        //如果允许改变分页
        if ($this->pagelock == false) {
            //传过来的分页大小
            if ($this->request['pagesize']) {
                while($this->request['pagesize']%5 != 0) $this->request['pagesize']++;
                if ($this->request['pagesize'] > 250) $this->request['pagesize'] = 250;
                if ($this->request['pagesize'] < 25) $this->request['pagesize'] = 25;

                //记住最近的页面大小
                setcookie('_ps', intval($this->request['pagesize']), time()+3600*24*365, '/');
            } else if ($this->cookie['_ps']) {
                $this->request['pagesize'] = intval($this->cookie['_ps']);
                while($this->request['pagesize']%5 != 0) $this->request['pagesize']++;
            }
        }

        //管理员可以看到下架商品
        if ($v['isadmin']) $data['isadmin'] = true;

        $data['sort']       = ($this->request['sort']       ? strtolower($this->request['sort']) : '');
        $data['sortorder']  = ($this->request['sortorder']  ? strtoupper($this->request['sortorder']) : 'ASC');
        $data['pagesize']   = ($this->request['pagesize'] ? $this->request['pagesize'] : $this->pagesize);
        $data['pid']        = intval($this->request['pid']);

        //代销
        if (isset($this->request['loopo_uid'])) $data['loopo_uid'] = intval($this->request['loopo_uid']);

        //搜索
        if ($this->clearSearchStr($this->request['s'])) $data['search'] = $this->clearSearchStr($this->request['s']);
        if ($this->_var['where']) $data['where'] = $this->_var['where'];

        //按价格搜索
        if ($this->request['pf'] || $this->request['pt']) {
            $data['pricefrom'] = (float)$this->request['pf'];
            $data['priceto']   = (float)$this->request['pt'];
            if ($data['pricefrom'] && ($data['priceto'] <= $data['pricefrom'])) $data['priceto'] = null;
        }

        //单个物品
        if (isset($this->request['id'])) {
            $data['ids'] = intval($this->request['id']);

            //NavBarPath
            //$itempath = $this->model->getPath($data['ids']);

            uses('cache');
            if (!$result = cache_get($data['ids'], 'items')) {
                //Tags
                $tags = $this->model->itemsTagsGet(array('id'=>$data['ids']));

                //Comments
                $c_ctrl =& getController('comments');
                $comments = $c_ctrl->commentList(array('iid'=>$data['ids'], 'pagesize'=>10));

                if ($tags)      $result['tags']     = $tags;
                if ($comments)  $result['comments'] = $comments;

                cache_set($data['ids'], $result, 'items');
            }
        }

        if ($this->request['ids']) {
            $this->request['ids'] = explode(',', $this->request['ids']);
            foreach ($this->request['ids'] as $id) $tmp[] = intval($id);
            $data['ids'] = join(',', $tmp);
        }

        $result = array_merge((array)$result, $data);
        unset($this->session['sig']['click']);
        $result['list'] = $this->model->itemsList($data);

        //Groups
        if ($this->request['id'] && $result['list']['list'][0]['groupkey']) $result['groups'] = $this->model->getGroups($result['list']['list'][0]['groupkey']);

        return $result;
    }

    function catsList() {
        uses('cache');

        $data['sort']       = ($this->request['sort'] ? strtolower($this->request['sort']) : '');
        $data['sortorder']  = ($this->request['sortorder'] ? strtoupper($this->request['sortorder']) : 'ASC');

        //只显示父分类是 $_GET['pid'] 的条目
        if ($this->request['pid']) $data['pid'] = intval($this->request['pid']);

        $result = $data;

        if ( !$result['list'] = cache_get('cat'.intval($data['pid']), 'cats') ) {
            $result['list'] = $this->model->catsList($data);
            cache_set('cat'.$data['pid'], $result['list'], 'cats');
        }

        return $result;
    }

    function addToCar($iid=0) {
        $data['iid']        = intval($this->request['id']);
        if ($iid) $data['iid'] = $iid;
        $data['sessionid']  = trim($this->session['sid']);
        $data['uid']        = trim($this->session['id']);

        $result = $this->model->addToCar($data);

        $this->session['caramount'] = $result['count'];
        $this->session['carprice']  = $result['price'];

        return $result;
    }

    function alertMe() {
        /*
        1.成功
        2.失败
        4.参数不对
        8.没有这个产品
        16.Email格式错误
        32.已经登记过了
        */
        $data['iid']    = intval($this->request['id']);
        $data['email']  = trim($this->request['email']);

        if ($data['iid']) {
            if( $data['email'] && !preg_match($this->regexp['email'], $data['email'])) {
                unset($data['email']);
                $emailerr = true;
            }

            $result = $this->model->alertMe($data);
            if ($emailerr) $result['code']['alertMe'] = 16;
        } else {
            $result['code']['alertMe'] = 4;
        }

        $result['data'] = $data;

        return $result;
    }

    //到货通知列表
    function adminAlert() {
        $data['iid']        = intval($this->request['iid']);
        $data['pagesize']   = 20;
        $data['sort']       = ($this->request['sort'] ? strtolower($this->request['sort']) : '');
        $data['sortorder']  = ($this->request['sortorder'] ? strtoupper($this->request['sortorder']) : 'DESC');

        $result['list'] = $this->model->alertList($data);

        return $result;
    }

    function ajaxAddToCar($v) {
        parse_str($v, $this->request);
        $this->request = array_stripslashes($this->request);

        $result = $this->addToCar();

        $r =& $this->ajax->add_node('result');
        $r->set_data($result['code']['addToCar']);
        $c =& $this->ajax->add_node('count');
        $c->set_data($result['count']);
        $p =& $this->ajax->add_node('totalprice');
        $p->set_data($result['price']);
    }

    //登录后购物车更新
    function loginIntoShopcar() {
        $data['sessionid']  = $this->session['sid'];
        $data['uid']        = $this->session['id'];

        $this->model->updateShopcarUid($data);
    }

    //Taglist
    function tagsList() {
        return $this->request['name'] ? $this->tagList() : $this->tagsAllList();
    }

    //单个tag列表
    function tagList() {
        //用户自定义排序
        switch($this->request['o']) {
            case '1':           $sort = 'name'; $sortorder = 'asc'; break;
            case '2':           $sort = 'price1'; $sortorder = 'asc'; break;
            case '3':default:   $sort = 'updated'; $sortorder = 'desc'; break;
            case '4':           $sort = 'click'; $sortorder = 'desc'; break;
        }

        $data['sort']       = 'issale DESC,'.$sort;
        $data['sortorder']  = $sortorder;
        $data['tagname']    = trim($this->request['name']);
        $data['pagesize']   = 1000;

        $result = $this->model->itemsTagsList($data);
        $data['tagdesc'] = $result['row']['desc'];
        $result['data'] = $data;

        return $result;
    }

    function tagsAllList() {
        $data['sort']       = 'pinyin';
        $data['sortorder']  = 'asc';
        $data['pagesize']   = 1000;

        uses('cache');
        if ((!$result = cache_get('itemsTagsAllList')) && !$this->get['update']) { //主动更新
            $result = $this->model->itemsTagsList($data);
            cache_set('itemsTagsAllList', $result);
        }

        return $result;
    }

    function adminList() {
        $this->needAdmin();

        $this->request['sortorder'] = 'desc';
        $result = $this->itemsList(array('isadmin'=>true));

        //加入分类、按分类查看用
        $this->request['sortorder'] = 'asc';
        $tmp = $this->adminCatsList();
        $result['cats'] = $tmp['list'];

        return $result;
    }

    function adminEdit() {
        $this->needAdmin();

        $data['id']     = $this->request['id'];
        $data['remove'] = $this->request['remove'];
        $data['copy']   = $this->request['copy'];
        $data['add']    = $this->request['add'];
        $data['cats']   = $this->catsList();

        $result['data'] = $data;

        //旧数据
        if (!$data['add']) {
            $v['ids'] = $data['id'];
            $tmp = $this->model->itemsList($v);
            $old = $tmp['list'][0];
        }

        //In Place Editor
        if ($this->request['inplace'] == 1 && $data['id']) {
            $v['id']                    = $data['id'];
            $v['fields']['updated']     = time();
            $v['fields']['name']        = $old['name'];
            $v['fields']['stuff']       = $old['stuff'];
            $v['fields']['model']       = $old['model'];
            $v['fields']['stocknum']    = $old['stocknum'];

            if ($this->request['name'])     $return = $v['fields']['name'] = $this->request['name'];
            if ($this->request['stuff'])    $return = $v['fields']['stuff'] = $this->request['stuff'];
            if ($this->request['model'])    $return = $v['fields']['model'] = $this->request['model'];
            if ($this->request['price1'])   $return = $v['fields']['price1'] = floatval($this->request['price1']);

            if (isset($this->request['stocknum'])) {
                $v['fields']['stocknum'] = intval($this->request['stocknum']);

                if ($v['fields']['stocknum'] > 0) $v['fields']['issale'] = 1;
                $v['fields']['stocked'] = 0;

                //补货处理
                if ( $old && ($old['stocknum'] == 0) && ($v['fields']['stocknum'] > 0) ) $v['fields']['stocked'] = time();

                $return = (string)$v['fields']['stocknum'];
            }

            $result = $this->model->itemsEdit($v);
            die($result['code']['itemsEdit']==1 ? $return : '更新失败');
        }

        if ($this->post['pid1'] && $this->post['name'] && $this->post['stuff'] && isset($this->post['stocknum']) && isset($this->post['pricein']) && $this->post['price1'] && $this->post['desc'] || $data['remove'] || $data['copy']) {

            //自编型号
            if (!trim($this->post['model'])) {
                $maxid = $this->getMaxItemId();
                $this->post['model'] = 'LP'.$maxid++;
            }

            //个性属性
            if ($this->post['key1'] || $this->post['key2'] || $this->post['key3'] || $this->post['key4'] || $this->post['key5']) {
                $cols['key1'] = trim($this->post['key1']);
                $cols['key2'] = trim($this->post['key2']);
                $cols['key3'] = trim($this->post['key3']);
                $cols['key4'] = trim($this->post['key4']);
                $cols['key5'] = trim($this->post['key5']);
                $cols['val1'] = trim($this->post['val1']);
                $cols['val2'] = trim($this->post['val2']);
                $cols['val3'] = trim($this->post['val3']);
                $cols['val4'] = trim($this->post['val4']);
                $cols['val5'] = trim($this->post['val5']);
            }

            //主次分类
            $data['fields']['pid1']         = $this->post['pid1'];
            $data['fields']['pid2']         = $this->post['pid2'];

            $data['fields']['name']         = trim($this->post['name']);
            $data['fields']['title']        = trim($this->post['title']);
            $data['fields']['stuff']        = trim($this->post['stuff']);
            $data['fields']['model']        = trim($this->post['model']);
            $data['fields']['stocknum']     = intval($this->post['stocknum']);
            $data['fields']['pricein']      = floatval($this->post['pricein']);
            $data['fields']['price1']       = floatval($this->post['price1']);
            $data['fields']['price2']       = floatval($this->post['price2']);
            if (!$data['fields']['price2']) $data['fields']['price2'] = $data['fields']['price1'];
            $data['fields']['price3']       = floatval($this->post['price3']);
            $data['fields']['postfee']      = floatval($this->post['postfee']);

            //分组属性
            if (isset($this->post['groupkey']))    $data['fields']['groupkey']     = trim($this->post['groupkey']);
            if (isset($this->post['groupvalue']))  $data['fields']['groupvalue']   = trim($this->post['groupvalue']);

            //销售状态
            if (isset($this->post['issale'])) $data['fields']['issale'] = intval($this->post['issale']);

            if ($cols)
                $data['fields']['cols']     = serialize($cols);

            $data['fields']['desc']         = trim($this->post['desc']);
            $data['fields']['updated']      = time();

            //添加时间
            if ($data['add']) $data['fields']['created'] = time();


            //补货时间
            $data['fields']['stocked'] = 0;
            if ( $old && ($old['stocknum'] == 0) && ($data['fields']['stocknum'] > 0) ) $data['fields']['stocked'] = time();

            $result = $this->model->itemsEdit($data);
            $result['ajaxcode'] = 1;

            //图片上传
            $uploadpath = ROOT.'images'.DS.'items'.DS;
            foreach ($_FILES["pic"]["error"] as $key => $error) if ($error == UPLOAD_ERR_OK) {
                //小图
                if ($key == 's') {
                    move_uploaded_file($_FILES['pic']['tmp_name'][$key], $uploadpath.$key.DS.$this->post['model'].'.gif');
                    chmod($uploadpath.$key.DS.$this->post['model'].'.gif', 0644);
                    //删除自动生成的缩略图
                    if (!$data['add']) {
                        @unlink($uploadpath.'thumb'.DS.'60'.DS.$this->post['model'].'.png');
                        @unlink($uploadpath.'thumb'.DS.'90'.DS.$this->post['model'].'.png');
                        @unlink($uploadpath.'thumb'.DS.'120'.DS.$this->post['model'].'.png');
                    }
                }
                //中图
                if ($key == 'm') {
                    move_uploaded_file($_FILES['pic']['tmp_name'][$key], $uploadpath.$key.DS.$this->post['model'].'.jpg');
                    chmod($uploadpath.$key.DS.$this->post['model'].'.jpg', 0644);
                }
            }

            //TAGS 处理
            if ($result['newid']) $data['id'] = $result['newid'];
            $data['tags']   = trim($this->post['tags']);
            if ($data['tags']) $this->model->itemsTagsUpdate($data);

            cache_delete('itemsTagsAllList'); //tag 列表 cache 更新
            cache_delete($data['id'], 'items'); //单个商品 cache 更新

            if ($result['remove'] || $result['add'] || $result['copy']) $this->redirect('items.php'.($this->request['p'] ? '?p='.$this->request['p'] : ''));
        } else {
            $result['ajaxcode'] = 2;
        }

        if (!$data['add']) {
            $v['ids'] = $data['id'];
            $tmp = $this->model->itemsList($v);
            $result['data'] = &$tmp['list'][0];

            //Tag更新
            $tmp = $this->model->itemsTagsGet($data);
            if (count($tmp)) {
                foreach ($tmp as $tmpv) $tmptag[] = $tmpv['name'];
                $result['data']['tags'] = join(' ', $tmptag);
            }

            //物品当前所属分类
            $result['mycats'] = $this->model->getItemsClass($data['id']);
            if (!$result['mycats']) {
                $result['mycats'][] = $this->post['pid1'];
                $result['mycats'][] = $this->post['pid2'];
            }
        }

        //分类
        $result['cats'] = $data['cats']['list'];

        return $result;
    }

    function ajaxAdminEdit($var) {
        parse_str($var, $this->post);
        $this->post = array_stripslashes($this->post);
        $result = $this->adminEdit();

        $this->ajax->quickresult($result['ajaxcode']);
    }

    function adminCatsList() {
        $this->needAdmin();

        $this->request['pid'] = 0;
        return $this->catsList();
    }

    function adminCatsAdd() {
        $this->needAdmin();

        $data['pid']    = trim($this->request['pid']);
        $data['name']   = trim($this->request['name']);
        if($this->post['desc']) $data['desc'] = trim($this->post['desc']);
        //$this->request['toppid'] = true;

        $tmp = $this->adminCatsList();
        $result['cats'] = $tmp['list'];

        if ($this->post && $data['name']) {
            /*
            1.成功
            2.失败
            */
            $result = $this->model->catsAdd($data);
            uses('cache');
            cache_delete('cat'.$data['pid'], 'cats');
            cache_delete('cat'.$result['id'], 'cats');
            if ($result['code']['catsAdd'] == 1) $this->redirect('itemscats.php');
        }
        $result['data'] = $data;

        return $result;
    }

    function adminCatsEdit() {
        $this->needAdmin();
        uses('cache');

        $data['id']     = $this->request['id'];
        $data['remove'] = $this->request['remove'];
        $this->request['toppid'] = true;

        $tmp = $this->adminCatsList();
        $result['cats'] = $tmp['list'];

        $result['data'] = $data;

        if ($this->post || $data['remove']) {
            $data['fields']['pid']  = intval($this->post['pid']);
            $data['fields']['name'] = trim($this->post['name']);
            if(isset($this->post['desc'])) $data['fields']['desc'] = trim($this->post['desc']);

            $result = $this->model->catsEdit($data);

            //Cache delete
            if (isset($data['fields']['pid']))  cache_delete('cat'.$data['fields']['pid'], 'cats');
            if (isset($data['fields']['id']))   cache_delete('cat'.$data['fields']['id'], 'cats');

            $this->redirect('itemscats.php');
        }

        $v['ids'] = $data['id'];
        $tmp = $this->model->catsList($v);
        $result['data'] = &$tmp['list'][0];

        return $result;
    }

    //上下架状态
    function adminToggleStat() {
        $this->needAdmin();

        $v['ids'] = (int)$this->request['iid'];
        $tmp = $this->model->itemsList($v);
        $old = $tmp['list'][0];

        if ($old['id']) {
            $v['id']                    = $old['id'];
            $v['fields']['groupkey']    = $old['groupkey'];
            $v['fields']['issale']      = $old['issale']==1 ? 0 : 1;
            $v['fields']['updated']     = time();
            $result = $this->model->itemsEdit($v);

            return $result;
        }
        return false;
    }

    function ajaxAdminToggleStat($var) {
        parse_str($var, $this->request);
        $this->request = array_stripslashes($this->request);

        $result = $this->adminToggleStat();

        $this->ajax->quickresult($result['code']['itemsEdit']);
    }

    function getMaxItemId() {
        return $this->model->getMaxId();
    }
}
?>
